﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.AccountsUsersModel;
using Aliyeye.Car.Net.UI.Components;
using Aliyeye.Car.Net.UI.PopupDialog;
using Aliyeye.Car.Net.Utility;
using Aliyeye.Car.Net.UI.Common;

namespace Aliyeye.Car.Net.UI.AdminCustomer
{
    public partial class UserPass : BaseForm
    {
        //private bool isDriver = false;
        private string strSearch = string.Empty;
        private int driverRole = 0;
        DataSet dtDepart = null;
        DataSet dtRole = null;
        private int UserId = 0;

        Base_DepartmentSvc.SoapHeaderClass sopaHeaderDepart = new Aliyeye.Car.Net.UI.Base_DepartmentSvc.SoapHeaderClass();
        AccountsUsersSvc.SoapHeaderClass sopaHeaderUsers = new Aliyeye.Car.Net.UI.AccountsUsersSvc.SoapHeaderClass();
        Accounts_RolesSvc.SoapHeaderClass sopaHeaderRole = new Accounts_RolesSvc.SoapHeaderClass();


        public UserPass()
        {
            InitializeComponent();
        }

        private void UserPass_Load(object sender, EventArgs e)
        {
            GetDriverRole();
            BindComboBoxInfo();
            this.pager1.PageCurrent = 1;
            this.pager1.Bind();
        }

        private void BindComboBoxInfo()
        {
            overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;
            Cursor.Current = Cursors.WaitCursor;
            string strWhere = string.Empty;
            DataSet dtRole = null;

            ServiceManipulator.SafeAsyncExecution<Accounts_RolesSvc.Accounts_RolesServiceSoapClient>(
                proxy => proxy.GetList(sopaHeaderRole, strWhere),
                result =>
                {
                    if (result.Error == null)
                    {
                        dtRole = (DataSet)result.Result;
                        cbbRole.DisplayMember = "Description";
                        cbbRole.ValueMember = "RoleID";
                        cbbRole.DataSource = dtRole.Tables[0];
                        cbbRole.SelectedIndex = 0;

                        overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                },
                this
            );

            DataSet dtDepart = null;
            ServiceManipulator.SafeAsyncExecution<Base_DepartmentSvc.Base_DepartmentServiceSoapClient>(
                proxy => proxy.GetList(sopaHeaderDepart, ""),
                result =>
                {
                    if (result.Error == null)
                    {
                        dtDepart = (DataSet)result.Result;
                        cbbDepart.DisplayMember = "ClassName";
                        cbbDepart.ValueMember = "ClassID";
                        cbbDepart.DataSource = dtDepart.Tables[0];
                        cbbDepart.SelectedIndex = 0;

                        overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        private void GetDriverRole()
        {
            Accounts_RolesSvc.Accounts_RolesServiceSoapClient client = new Aliyeye.Car.Net.UI.Accounts_RolesSvc.Accounts_RolesServiceSoapClient();

            string strWhere = string.Empty;
            DataSet dtRole = null;
            strWhere = "Description ='驾驶员'";
            dtRole = client.GetList(sopaHeaderRole, strWhere);
            if (dtRole.Tables[0].Rows.Count > 0)
            {
                if (dtRole.Tables[0].Rows[0]["RoleID"].ToString() != "")
                {
                    driverRole = int.Parse(dtRole.Tables[0].Rows[0]["RoleID"].ToString());
                }
            }
        }

        private int dgvBind()
        {
            string _strSql = "";
            string strWhere = strSearch;
            PageData pageData = new PageData(this, pager1, this.overlay);
            pageData.TableName = "Accounts_Users left join Accounts_Roles on Accounts_Roles.RoleID=Accounts_Users.RoleId " +
                "left join Base_Department on Base_Department.ClassID=Accounts_Users.DepID";
            pageData.PrimaryKey = "Accounts_Users.UserID";
            pageData.OrderStr = "Accounts_Users.UserID desc";
            pageData.PageIndex = this.pager1.PageCurrent;
            pageData.PageSize = this.pager1.PageSize;
            pageData.QueryCondition = _strSql + strWhere.ToString();
            pageData.QueryFieldName = "Accounts_Users.UserID,Accounts_Users.RoleId,Accounts_Users.UserName,Accounts_Users.TrueName,Accounts_Users.Sex,Accounts_Users.State,Accounts_Users.Tel,Accounts_Roles.Description, Base_Department.ClassName";

            dgvInfo.AutoGenerateColumns = false;
            DataSet ds = pageData.QueryDataTable();
            dgvInfo.DataSource = this.pager1.bindingSource;
            return pageData.TotalCount;
        }


        private int pager1_EventPaging(Aliyeye.Car.Net.UI.Components.EventPagingArg e)
        {
            return dgvBind();
        }

        private void dgvInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (IsANonHeaderButtonCell(e))
            {
                ButtonClicked(e);
            }
        }

        private void ButtonClicked(DataGridViewCellEventArgs e)
        {
            String strButtonContent = dgvInfo.Columns[e.ColumnIndex].Name;
            String id = dgvInfo.Rows[e.RowIndex].Cells["编号"].Value.ToString();
            int driverRoleID = Convert.ToInt32(dgvInfo.Rows[e.RowIndex].Cells["RoleId"].Value.ToString());

            if (strButtonContent.Trim().Equals("设置密码"))
            {
                UserId = Convert.ToInt32(id);
                panel1.Visible = true;
            }
            else if (strButtonContent.Trim().Equals("查看"))
            {
                if (driverRole == driverRoleID)
                {
                    UserInfo userForm = new UserInfo(true, Convert.ToInt32(id));
                    userForm.ShowDialog();
                }
                else
                {
                    UserInfo userForm = new UserInfo(false, Convert.ToInt32(id));
                    userForm.ShowDialog();
                }
            }
            this.pager1.Bind();
        }
        private bool IsANonHeaderButtonCell(DataGridViewCellEventArgs cellEvent)
        {
            if (dgvInfo.Columns[cellEvent.ColumnIndex] is
                 DataGridViewButtonColumn &&
                 cellEvent.RowIndex != -1)
            { return true; }
            else { return (false); }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string strWhere = "";
            if (!string.IsNullOrEmpty(txtUserName.Text))
            {
                strWhere += " And UserName like '%" + txtUserName.Text + "%'";
            }

            if (!string.IsNullOrEmpty(txtTrueName.Text))
            {
                strWhere += " And TrueName like '%" + txtTrueName.Text + "%'";
            }

            if (!string.IsNullOrEmpty(cbbDepart.SelectedValue.ToString()))
            {
                strWhere += " And DepID = '" + cbbDepart.SelectedValue.ToString() + "'";
            }

            if (!string.IsNullOrEmpty(cbbRole.SelectedValue.ToString()))
            {
                strWhere += " And RoleId = '" + cbbRole.SelectedValue.ToString() + "'";
            }

            this.pager1.Bind();
        }

        private void btnAll_Click(object sender, EventArgs e)
        {
            strSearch = "";
            this.pager1.Bind();
        }

        private void dgvInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;
            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "状态")
            {
                if (e.Value != null)
                {
                    if (Convert.ToBoolean(e.Value))
                    {
                        e.Value = "使用中";
                    }
                    else
                    {
                        e.Value = "禁用中";
                    }
                }
            }
        }

        private void dgvInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvInfo.Rows.Count; )
                {
                    this.dgvInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        private void menuBlueButton1_Click(object sender, EventArgs e)
        {
            if (txtpass.Text.ToLower() == textBox1.Text.ToLower())
            {
                overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;
                Cursor.Current = Cursors.WaitCursor;
                AccountsUsersSvc.Accounts_Users model = new AccountsUsersSvc.Accounts_Users();
                model.UserID = UserId;
                model.Password = JhEncrypt.EncryptPassword(txtpass.Text);

                ServiceManipulator.SafeAsyncExecution<AccountsUsersSvc.Accounts_UsersServiceSoapClient>(
                    proxy => proxy.UpdatePass(sopaHeaderUsers, model),
                    result =>
                    {
                        if (result.Error == null)
                        {
                            PageCommon.Notify("密码设置成功！");
                            panel1.Visible = false;
                            overlay.FadeOut();Cursor.Current = Cursors.Default;
                        }
                        else
                        {
                            PageCommon.Error(result.Error.Message);
                            overlay.FadeOut();Cursor.Current = Cursors.Default;
                        }
                    },
                    this
                );
            }
            else
            {
                this.textBox1.Text = "";
                txtpass.Text = "";
                DialogNotify diaSecc = new DialogNotify("两次输入的密码不一致，请重新输入！");
                diaSecc.ShowDialog();
            }
        }

        private void menuBlueButton2_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        
    }
}
